// 新品榜单
import 'package:cbec_app/components/base/base_image.dart';
import 'package:cbec_app/pages/goods/controller/new_products_ranking_ctr.dart';
import 'package:get/get.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../../../components/common/common_style.dart';
import '../../../components/common/not_found.dart';
import '../../../routes/routes.dart';
import '../../../utils/Tools.dart';
import '../binding/goods_detail_binding.dart';
import 'goods_detail_page.dart';

class NewProductsRankingPage extends GetView<NewProductsRankingCtr> {
  const NewProductsRankingPage({super.key});
  @override
  Widget build(BuildContext context) {
    return GetBuilder<NewProductsRankingCtr>(builder: (controller) {
      return Scaffold(
        //extendBodyBehindAppBar: true, // 允许 body 从 AppBar 顶部开始布局
        backgroundColor: Tools.fromHex('#362819'),
        appBar: AppBar(
          centerTitle: true,
          title: Text(
            '新品榜单',
            style: TextStyle(fontWeight: FontWeight.w500, fontSize: 17, color: Tools.fromHex('#333333')),
          ),
          backgroundColor: Colors.white, // 设置透明
          leading: IconButton(
            icon: const Icon(
              Icons.arrow_back_ios,
              color: Colors.black,
            ),
            onPressed: () {
              Navigator.pop(context);
            },
          ),
        ),
        body: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            //自适应高度的图片
            Stack(
              children: [
                SizedBox(
                  width: double.infinity,
                  child: BaseImage(url: controller.newRankings),
                ),
                //const topRightBox(),
              ],
            ),

            if (controller.tabController != null) _topTabbar(),
            // 列表
            Expanded(
              child: controller.goodsList.isNotEmpty
                  ? Tools.getPullRefresh(
                      enablePullDown: true,
                      enablePullUp: true,
                      refreshController: controller.baseRefreshCtr,
                      onRefresh: controller.onPageRefresh,
                      onLoading: controller.onPageLoading,
                      child: ListView.builder(
                          controller: controller.scrollController,
                          padding: EdgeInsets.zero, // 移除默认的内边距
                          itemCount: controller.goodsList.length,
                          itemBuilder: (context, index) {
                            final Map item = controller.goodsList[index];
                            return _createItem(item, index);
                          }))
                  : const NotFound(),
            ),
          ],
        ),
      );
    });
  }

  Widget _topTabbar() {
    final NewProductsRankingCtr controller = Get.find<NewProductsRankingCtr>();
    var itemList = controller.itemList;
    return Container(
      color: Tools.fromHex('#362819'),
      height: 40,
      width: double.infinity,
      child: TabBar(
        indicator: const BoxDecoration(), // 空装饰，去掉下划线
        dividerColor: Colors.transparent,
        labelColor: Tools.fromHex('#F9CF57'),
        labelStyle: TextStyle(
          fontSize: 15,
          fontWeight: FontWeight.w700,
          color: Tools.fromHex('#F9CF57'),
        ),
        unselectedLabelColor: Colors.white,
        unselectedLabelStyle: const TextStyle(
          fontSize: 14,
          fontWeight: FontWeight.w300,
          color: Colors.white,
        ),
        controller: controller.tabController,
        tabAlignment: TabAlignment.fill,
        labelPadding: const EdgeInsets.symmetric(horizontal: 5),
        tabs: itemList.map<Widget>((item) {
          return Tab(
            text: item.label,
          );
        }).toList(),
      ),
    );
  }

  Widget _createItem(Map item, int index) {
    final assetMap = {
      0: 'assets/images/new_product_rank_one.png',
      1: 'assets/images/new_product_rank_two.png',
      2: 'assets/images/new_product_rank_three.png',
    };

    return GestureDetector(
      onTap: () {
        final id = item['goodsId'];
        Get.to(
          () => GoodsDetailPage(flag: id), // 使用函数懒加载页面实例
          routeName: '${Routes.goodsDetail}?unique=${DateTime.now().millisecondsSinceEpoch}',
          arguments: {"id": id}, // 传递其它参数
          binding: GoodsDetailBinding(flag: id), // 将 tag 参数传递给绑定类
        );
      },
      child: Container(
        color: Colors.transparent,
        child: Container(
          margin: const EdgeInsets.only(left: 10, right: 10, top: 10), // 添加外边距
          child: ClipRRect(
            borderRadius: BorderRadius.circular(8), // 设置圆角裁剪
            child: Container(
              decoration: const BoxDecoration(
                color: Colors.white, // 白色背景
              ),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start, // 使列顶部对齐
                children: [
                  Container(
                    padding: const EdgeInsets.all(10),
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(8),
                      child: Stack(
                        children: [
                          Image.network(item['mainImage'], width: 110, height: 110),
                          Positioned(
                            left: 0,
                            top: 0,
                            child: assetMap.containsKey(index) ? Image.asset(assetMap[index]!, width: 36, height: 36) : const SizedBox.shrink(),
                          ),
                        ],
                      ),
                    ),
                  ),
                  Expanded(
                    // 确保文本可以占据剩余空间
                    child: Container(
                      height: 130,
                      padding: const EdgeInsets.only(left: 10, right: 10, top: 5, bottom: 5), // 添加外边距
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        crossAxisAlignment: CrossAxisAlignment.start, // 左对齐文本
                        children: [
                          RichText(
                            text: TextSpan(
                              children: [
                                WidgetSpan(
                                  child: goodsTypeTag(
                                    getGoodsTypeName(item['commodityType']),
                                    margin: const EdgeInsets.only(right: 5), // 设置右边距
                                  ),
                                ),
                                TextSpan(
                                  text: item['commodityName'],
                                  style: TextStyle(
                                    fontSize: 14,
                                    fontWeight: FontWeight.normal,
                                    color: Tools.fromHex('#3D3D3D'),
                                  ),
                                ),
                              ],
                            ),
                            maxLines: 2, // 设置最大行数为 2
                            overflow: TextOverflow.ellipsis, // 超过部分显示省略号
                          ),

                          // 标签
                          Wrap(
                            runSpacing: 8.w,
                            spacing: 2,
                            children: [
                              for (var text in item['discountLabel']) goodsDetailTypeTag(text),
                            ],
                          ),

                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text.rich(
                                TextSpan(
                                  children: [
                                    TextSpan(
                                      text: '¥',
                                      style: TextStyle(
                                        color: Tools.fromHex('#F83F2D'),
                                        fontSize: 12, // 设置较小的字体大小
                                        fontWeight: FontWeight.w400,
                                      ),
                                    ),
                                    TextSpan(
                                      text: '${item['specialPrice']}',
                                      style: TextStyle(
                                        color: Tools.fromHex('#F83F2D'),
                                        fontSize: 15, // 设置较大的字体大小
                                        fontWeight: FontWeight.w700,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              IconButton(
                                  onPressed: () {
                                    final id = item['goodsId'];
                                    Get.to(
                                      () => GoodsDetailPage(flag: id), // 使用函数懒加载页面实例
                                      routeName: '${Routes.goodsDetail}?unique=${DateTime.now().millisecondsSinceEpoch}',
                                      arguments: {"id": id}, // 传递其它参数
                                      binding: GoodsDetailBinding(flag: id), // 将 tag 参数传递给绑定类
                                    );
                                  },
                                  icon: BaseImage(url: 'new_product_ranking_cart.png', width: 22, height: 22)),
                            ],
                          )
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}
